package com.serv.admin;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.kit.PropKit;
import com.serv.common.base.BaseController;
import com.serv.common.model.sys.User;
import com.serv.common.route.AdminAuthInterceptor;
import com.serv.common.service.sys.UserService;
import com.serv.util.AjaxObject;
import com.serv.util.Result;

@Before(AdminValidator.class)
public class AdminController extends BaseController {
	@Inject
	UserService userService;
	
	public void index() {
		User user = getSubject();
		setAttr("organizations", user.organization().children());
		render("index.html");
	}
	
	@Clear(AdminAuthInterceptor.class)
	public void timeout(){
		renderJson(AjaxObject.newTimeout("超时了，重新整吧"));
	}
	
	@Clear(AdminAuthInterceptor.class)
	public void login(){
		setAttr("captcha",PropKit.getBoolean("user.captcha",false));
		render("login.html");
	}
	
	@Clear(AdminAuthInterceptor.class)
	public void doLogin(String username,String password,String captcha){
		User user = userService.getByUsername(username);
		String encrypt = userService.encrypt(password,user.getStr("salt"));
		if(encrypt.equals(user.getStr("password"))){
			setSubject(user);
			renderJson(Result.success("登录成功",getRequest().getContextPath()+"/"));
		}else{
			renderJson(Result.error("账号或密码错误"));
		}
	}
	
	@Clear(AdminAuthInterceptor.class)
	public void loginDialog(){
		setAttr("captcha",PropKit.getBoolean("user.captcha",false));
		render("login_dialog.html");
	}
	
	@Clear(AdminAuthInterceptor.class)
	public void doLoginDialog(String username,String password,String captcha){
		User user = userService.getByUsername(username);
		String encrypt = userService.encrypt(password,user.getStr("salt"));
		if(encrypt.equals(user.getStr("password"))){
			setSubject(user);
			renderJson(AjaxObject.newOk("登录成功"));
		}else{
			renderJson(AjaxObject.newError("账号或密码错误"));
		}
	}
	
	public void userTreeByOrg(){
		
	}
	
	public void logout(){
		resetSubject();
		redirect("/login");
	}
	
	@Clear(AdminAuthInterceptor.class)
	public void captcha(){
		renderCaptcha();
	}
}
